<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <!-- :span 为搜索框设置长度 -->
        <el-col :span="10">
          <!-- 搜索与添加区域 在按钮上绑定keyup事件，加上.native覆盖原有封装的keyup事件-->
          <el-input placeholder="请输入内容" v-model="queryInfo.query"
          clearable @clear="getManagerList"
          @keyup.native.enter="getManagerList"
          @keyup.native.backspace="getManagerList">
            <el-button slot="append" icon="el-icon-search"
            @click="getManagerList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    <!-- 表格区 -->
    <el-table :data="managerList" border stripe>
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="id" prop="mgId" width="80px"></el-table-column>
      <el-table-column label="姓名" prop="mgName"></el-table-column>
      <el-table-column label="密码" prop="mgPwd"></el-table-column>
      <el-table-column label="电话" prop="mgMobile"></el-table-column>
      <el-table-column label="邮箱" prop="mgEmail"></el-table-column>
      <el-table-column label="创建时间" prop="mgTime"></el-table-column>
      <el-table-column label="状态">
        <!-- slot-scope="scope"获取当前行的所有数据 然后点出想要的数据 -->
        <template slot-scope="scope">
          <el-switch :active-value=1 :inactive-value=0 v-model="scope.row.mgState"
          @change="managerStateChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <!-- 修改按钮样式 -->
          <el-button type="primary" icon="el-icon-edit" size="mini"
          @click="showEditDialog(scope.row)"></el-button>
          <!-- 删除按钮 -->
          <el-button type="danger" icon="el-icon-delete" size="mini"
          @click="removeManagerById(scope.row.mgId)"></el-button>
          <!-- 设置样式 -->
          <el-tooltip effect="dark" content="Top Left 分配角色"
          placement="top-start">
            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区 -->
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pageNo"
      :page-sizes="[2, 5, 10, 20]"
      :page-size="queryInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
     </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%" @close="addDialogClosed">
      <!-- 内容主题区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
      label-width="70px">
        <el-form-item label="用户名" prop="mgName">
          <el-input v-model="addForm.mgName"></el-input>
        </el-form-item>
          <el-form-item label="密码" prop="mgPwd">
          <el-input v-model="addForm.mgPwd"></el-input>
        </el-form-item>
          <el-form-item label="邮箱" prop="mgEmail">
          <el-input v-model="addForm.mgEmail"></el-input>
        </el-form-item>
          <el-form-item label="手机号" prop="mgMobile">
          <el-input v-model="addForm.mgMobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addManager">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="addFormRules" ref="editFormRef"
      label-width="70px">
        <el-form-item label="用户名" prop="mgName">
          <el-input v-model="editForm.mgName" disabled></el-input>
        </el-form-item>
          <el-form-item label="密码" prop="mgPwd">
          <el-input v-model="editForm.mgPwd"></el-input>
        </el-form-item>
          <el-form-item label="邮箱" prop="mgEmail">
          <el-input v-model="editForm.mgEmail"></el-input>
        </el-form-item>
          <el-form-item label="手机号" prop="mgMobile">
          <el-input v-model="editForm.mgMobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editManager">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 校验邮箱的规则
    var checkEmail = (rules, value, callback) => {
      const regEmail = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('邮箱格式错误'))
    }
    // 校验手机号的规则
    var checkMobile = (rules, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('手机号格式错误'))
    }
    return {
      // 定义入参
      queryInfo: {
        pageNo: 1,
        pageSize: 5,
        query: ''
      },
      managerList: [],
      total: 0,
      switchValue: false,
      managerParams: {
        mgId: 0,
        mgState: 0
      },
      // 控制对话框的显示与隐藏
      addDialogVisible: false,
      // 控制对话框的显示与隐藏
      editDialogVisible: false,
      // 添加用户的表单内容
      addForm: {
        mgName: '',
        mgPwd: '',
        mgEmail: '',
        mgMobile: ''
      },
      editForm: {
        mgName: '',
        mgPwd: '',
        mgEmail: '',
        mgMobile: '',
        mgId: '',
        mgState: ''
      },
      // 添加用户的表单验证规则
      addFormRules: {
        mgName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        mgPwd: [
          { required: true, message: '密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        mgEmail: [
          { required: true, message: '邮箱', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在3-50位以内', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mgMobile: [
          { required: true, message: '手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '输入手机格式有误', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getManagerList()
  },
  methods: {
    async getManagerList () {
      const { data: res } = await this.$http.post('/manager/selectAll', this.queryInfo)
      // console.log(res)
      if (res.code !== '0') return this.$message.error('获取用户列表失败！')
      this.managerList = res.data.records
      this.total = res.data.total
    },
    // 监听pageSize改变的事件
    handleSizeChange (newSize) {
      // console.log(newSize)
      // 赋值给新的请求条数，异步重新调用接口
      this.queryInfo.pageSize = newSize
      this.getManagerList()
    },
    // 监听页码值发生改变的事件
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pageNo = newPage
      this.getManagerList()
    },
    // 监听switch开关 状态的改变
    async managerStateChange (managerInfo) {
      // console.log(managerInfo)
      this.managerParams.mgId = managerInfo.mgId
      this.managerParams.mgState = managerInfo.mgState
      const { data: res } = await this.$http.post('/manager/update', this.managerParams)
      // console.log(res)
      if (res.code !== '0') {
        // 更新失败 应该把switch开关取反 还原回去
        managerInfo.mgState = !managerInfo.mgState
        return this.$message.error('更新用户信息失败')
      }
      this.$message.success('更新用户信息成功')
    },
    // 监听用户对话框关闭的事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    addManager () {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // console.log(this.addForm)
        const { data: res } = await this.$http.post('/manager/insert', this.addForm)
        // console.log(res)
        if (res.code !== '0') return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 隐藏添加用户列表对话框
        this.addDialogVisible = false
        // 重新获取用户列表
        this.getManagerList()
      })
    },
    // 展示编辑用户的对话框
    showEditDialog (manager) {
      this.editDialogVisible = true
      // console.log(manager)
      this.editForm.mgPwd = manager.mgPwd
      this.editForm.mgName = manager.mgName
      this.editForm.mgEmail = manager.mgEmail
      this.editForm.mgMobile = manager.mgMobile
      this.editForm.mgState = manager.mgState
      this.editForm.mgId = manager.mgId
    },
    // 修改用户信息并提交
    editManager () {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('/manager/update', this.editForm)
        console.log(res)
        if (res.code !== '0') return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        // 隐藏添加用户列表对话框
        this.editDialogVisible = false
        // 重新获取用户列表
        this.getManagerList()
      })
    },
    // 根据id删除用户信息
    async removeManagerById (id) {
      // console.log(id)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
      // 如果确认删除返回confirm 如果取消返回concel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.get('/manager/delete?mgId=' + id)
      console.log(res)
      if (res.code !== '0') {
        return this.$message.error('删除失败!')
      }
      this.$message.success('删除成功！')
      this.getManagerList()
    }
  }
}
</script>

<style lang="stylus" scoped></style>
